﻿using System;
using EPiServer;
using EPiServer.Core;
using JoelAbrahamsson.PageTypes;

namespace JoelAbrahamsson.Web
{
    public class CurrentPageResolver
    {
        public BasePageData GetCurrentPage(string slug)
        {
            BasePageData page = null;

            if (PossiblyWorkPage(slug))
            {
                page = GetWorkPage(slug);
            }

            if (page == null)
                page = GetPageBySlug(slug, PageReference.StartPage);

            return page;
        }

        private bool PossiblyWorkPage(string slug)
        {
            return slug.Contains("_");
        }

        private BasePageData GetWorkPage(string slug)
        {
            BasePageData page = null;

            string[] splitSlug = slug.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries);

            int pageID;
            if (splitSlug.Length > 1 && int.TryParse(splitSlug[0], out pageID))
            {
                int workPageID;
                if (int.TryParse(splitSlug[1], out workPageID))
                {
                    PageReference workPageReference = new PageReference(pageID, workPageID);
                    page = (BasePageData)DataFactory.Instance.GetPage(workPageReference);
                }
            }

            return page;
        }

        protected BasePageData GetPageBySlug(string slug, PageReference startingPoint)
        {
            BasePageData pageToCheck = (BasePageData)DataFactory.Instance.GetPage(startingPoint);
            if (pageToCheck.Slug.Equals(slug, StringComparison.OrdinalIgnoreCase))
                return pageToCheck;

            PageDataCollection children = DataFactory.Instance.GetChildren(pageToCheck.PageLink);
            foreach (PageData child in children)
            {
                PageData matchedDescendant = GetPageBySlug(slug, child.PageLink);
                if (matchedDescendant != null)
                    return (BasePageData)matchedDescendant;
            }

            return null;
        }
    }
}
